import os
import json
from argparse import ArgumentParser


def read_userdata(path=None):
    if path is None:
        path = os.environ.get("PINFRAC_USERDATA", ".") + "/data.json"
    try:
        with open(path, "r") as fp:
            data:dict = json.load(fp)
    except FileNotFoundError:
        data = dict()
    return data


def write_userdata(data, path=None):
    if path is None:
        path = os.environ.get("PINFRAC_USERDATA", ".") + "/data.json"

    with open(path, "w") as fp:
        json.dump(data, fp, indent=4)


def main():
    argp = ArgumentParser()
    argp.add_argument("--path", type=str, default=None)
    argp.add_argument("--default", type=eval, default=None)
    argp.add_argument("--delete", action="store_true")
    argp.add_argument("key", type=str)
    argp.add_argument("value", type=eval, nargs="?", default=None)
    args = argp.parse_args()

    data = read_userdata(args.path)

    # get
    if args.delete == False and args.value is None:
        print(data.get(args.key, args.default))
        exit(0)
        
    # set
    if args.delete == False and args.value is not None:
        data[args.key] = args.value
        
    # delete
    if args.delete:
        data.pop(args.key)
    
    # writeback
    write_userdata(data, path=args.path)

    exit(0)

if __name__ == "__main__":
    main()
